<template>
  <div class="theme-content-item" style="position: relative;">
    <div class="padding-20px">
      <div class="left-title">{{ title }}</div>
      <el-form ref="formRef" label-width="120px" :model="form" :rules="rules"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="10">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="排序" prop="orderNum">
              <el-input type="number" v-model="form.orderNum" placeholder="请输入排序号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="年份" prop="examYear">
              <el-date-picker
                  v-model="form.examYear"
                  value-format="YYYY"
                  type="year"
                  placeholder="请选择年份"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10" >
            <el-form-item label="类型" prop="categoryId">
              <el-select clearable v-model="form.categoryId" placeholder="请选择类型">
                <el-option v-for="item in data.categoryList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="有效期" prop="validDateRange">
              <el-date-picker
                  v-model="form.validDateRange"
                  type="daterange"
                  range-separator="-"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="老师" prop="teacherIdList">
              <el-select multiple clearable v-model="form.teacherIdList" placeholder="请选择老师">
                <el-option v-for="item in data.teacherList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="标签" prop="tagLabel">
              <el-input v-model="form.tagLabel" placeholder="请输入标签"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="亮点" prop="tagHighlightIdList">
              <el-select multiple clearable v-model="form.tagHighlightIdList" placeholder="请选择特色">
                <el-option v-for="item in data.tagHighlightList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="特色" prop="tagServiceIdList">
              <el-select multiple clearable v-model="form.tagServiceIdList" placeholder="请选择亮点">
                <el-option v-for="item in data.tagServiceList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="价格" prop="realPrice">
              <el-input type="number" v-model="form.realPrice" :min="1" placeholder="请输入价格"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="封面" prop="picUrl">
              <ImgUpload v-model="form.picUrl"></ImgUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div style="border: 1px solid #ccc;height:600px">
        <Toolbar style="border-bottom: 1px solid #ccc" ref="editorRef" :editor="editorData"
                 :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="overflow-y:scroll;height:calc(100% - 70px)" v-model="form.descr"
                :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
      </div>

      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {listDictItemByCode} from '@/api/config/dic'
import {listTeacher} from '@/api/teacher'
import {addCourse, editCourse} from "@/api/course";
import {ElMessage} from "element-plus";
import {getCourseDetail} from "@/api/course";
import ImgUpload from "../../../common/component/upload/img-upload";
import useEditor from "../../../common/component/rich/editor"
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {addGoods, editGoods, getGoodsDetail} from "../../../../api/goods";

const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const title = ref('')
const isAdd = ref(true)

const { toolbarConfig, editorConfig, editorData, handleCreated, destroyEditor } = useEditor()

const data = reactive({
  categoryList: [],
  kindList: [],
  teacherList: [],
})
const form = reactive({
  id: null,
  orderNum: '',
  name: '',
  examYear: '',
  categoryId: '',
  teacherIdList: [],
  publishedFlag: '',
  tagLabel: '',
  realPrice: '',
  picUrl: ''
})

const rules = ({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  orderNum: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  examYear: [{ required: true, message: '请选择年份', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择课程类型', trigger: 'blur' }],
  validDateRange: [{ required: true, message: '请选择有效期', trigger: 'blur' }],
  teacherIdList: [{ required: true, message: '请选择老师', trigger: 'blur' }],
  tagLabel: [{ required: true, message: '请输入标签', trigger: 'blur' }],
  tagHighlightIdList: [{ required: true, message: '请选择亮点', trigger: 'blur' }],
  realPrice: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  picUrl: [{ required: true, message: '请选择封面', trigger: 'blur' }],
})

// 详情
const initDetail = () => {
  getGoodsDetail(route.query.id).then((res) => {
    let resData = res.data
    Object.keys(form).forEach((key) => { form[`${key}`] = resData[`${key}`] })

    form.examYear = resData.examYear + ""
    form.validDateRange = [resData.validStartTime, resData.validEndTime]
    let highlightIdList = []
    let highlightList = resData.tagHighlightList
    if (highlightList) {
      highlightList.forEach((item)=>{
        highlightIdList.push(item.id)
      })
    }
    let serviceIdList = []
    let serviceList = resData.tagServiceList
    if (serviceList) {
      serviceList.forEach((item)=>{
        serviceIdList.push(item.id)
      })
    }
    form.tagHighlightIdList = highlightIdList
    form.tagServiceIdList = serviceIdList
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.categoryList = res.rows
  })
  listDictItemByCode({typeCode: 'goodsHighlightsCode'}).then(res => {
    data.tagHighlightList = res.rows
  })
  listDictItemByCode({typeCode: 'goodsFeatureCode'}).then(res => {
    data.tagServiceList = res.rows
  })
  listTeacher({}).then(res => {
    data.teacherList = res.rows
  })
}

const save = () => {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      let requestData = {}
      Object.keys(form).forEach((key) => { requestData[`${key}`] = form[`${key}`] })
      let highlightIdList = requestData.tagHighlightIdList
      let tagHighlightList = data.tagHighlightList
      let highlightList = []
      if (highlightIdList) {
        highlightIdList.forEach((id)=>{
          let value = tagHighlightList.find((item)=>item.id == id)
          if (value) {
            highlightList.push({id: id, name: value.name})
          }
        })
      }
      requestData.tagHighlightList = highlightList

      let serviceIdList = requestData.tagServiceIdList
      let tagServiceList = data.tagServiceList
      let serviceList = []
      if (serviceIdList) {
        serviceIdList.forEach((id)=>{
          let value = tagServiceList.find((item)=>item.id == id)
          if (value) {
            serviceList.push({id: id, name: value.name})
          }
        })
      }
      requestData.tagServiceList = serviceList

      let dateRange = requestData.validDateRange
      if (dateRange && dateRange.length == 2) {
        let startTime = dateRange[0]
        let endTime = dateRange[1]
        requestData.validStartTime = startTime
        requestData.validEndTime = endTime
      }

      if (isAdd.value) {
        requestData.publishedFlag = 0
        addGoods(requestData).then((res) => {
          reset()
          ElMessage.success('操作成功');
        })
      }else{
        editGoods(requestData).then((res)=>{
          ElMessage.success('操作成功');
        })
      }
    }
  })
}

const reset = () => {
  form.teacherIdList = []
  form.categoryId = ''
}

function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}

onMounted(() => {
  let titleMap = {
    add: '新增',
    edit: '修改',
  }
  let type = routeQuery.type
  let titleValue = '新增'
  if (type) {
    titleValue = titleMap[routeQuery.type]
  }
  title.value = titleValue
  isAdd.value = routeQuery.type != 'edit'
  if (!isAdd.value) {
    initDetail()
  }

  initData()
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  destroyEditor()
})

</script>
<style scoped lang="scss">
:deep(.el-input) {
  width: 400px;
}
:deep(.el-input__wrapper) {
  width: 400px;
}
</style>
